package com.valuegroup.smarttodo.ui.todo.task.detail;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.android.material.snackbar.Snackbar;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.Remark;
import com.valuegroup.smarttodo.data.model.Task;
import com.valuegroup.smarttodo.data.model.TaskStep;
import com.valuegroup.smarttodo.data.vo.TaskStepVo;
import com.valuegroup.smarttodo.plugins.ClickableTextView;
import com.valuegroup.smarttodo.plugins.MultilineEditText;
import com.valuegroup.smarttodo.plugins.pickdialog.DatePickDialog;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.pickdialog.OnCustomSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.OnSureLisener;
import com.valuegroup.smarttodo.plugins.pickdialog.bean.DateType;
import com.valuegroup.smarttodo.plugins.recyclerview.ItemTouchHelperAdapter;
import com.valuegroup.smarttodo.plugins.recyclerview.ItemTouchHelperViewHolder;
import com.valuegroup.smarttodo.util.AlertUtils;
import com.valuegroup.smarttodo.util.Typefaces;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 任务详情步骤列表
 */
public class TaskDetailAdapter extends RecyclerView.Adapter implements ItemTouchHelperAdapter {

    private static final String TAG = TaskDetailAdapter.class.getSimpleName();

    private final Context mContext;
    private final View view;
    private Task DATA;
    private List<TaskStepVo> datas;

    public TaskDetailAdapter(Context context, View view, Long taskId) {
        this.mContext = context;
        this.view = view;
        this.DATA = ServiceFactory.getInstance().getTaskService().load(taskId);
        this.datas = ServiceFactory.getInstance().getTaskService().findTaskStepForDetail(taskId);
    }

    public Context getmContext() {
        return mContext;
    }

    @Override
    public void onItemDismiss(final int position, boolean isLeftSlide) {
        if (getItemViewType(position) != TYPE_CONTENT) {
            return;
        }

        final int listPosition = position - START_COUNT;
        TaskStep step = ServiceFactory.getInstance().getTaskService().getTaskStep(datas.get(listPosition).getId());
        final TaskStepVo item = TaskStepVo.convertTaskStep(step);

        datas.remove(listPosition);
        notifyItemRemoved(position);
        notifyItemRangeChanged(0, getContentSize());

        // 删除数据
        ServiceFactory.getInstance().getTaskService().delTaskStep(step.getId());

        final Snackbar snackbar = Snackbar
                .make(view, getmContext().getResources().getString(R.string.item_deleted), Snackbar.LENGTH_LONG)
                .setActionTextColor(Color.WHITE)
                .setAction(getmContext().getResources().getString(R.string.item_undo), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        datas.add(listPosition, item);
                        notifyItemInserted(position);

                        // 撤销删除
                        ServiceFactory.getInstance().getTaskService().addTaskStep(TaskStepVo.convertTaskStep(step));
                    }
                });

        View snackBarView = snackbar.getView();
        snackBarView.setBackgroundColor(ContextCompat.getColor(getmContext(), R.color.colorPrimary));
        TextView tvSnack = snackBarView.findViewById(R.id.snackbar_text);
        TextView tvSnackAction = snackbar.getView().findViewById(R.id.snackbar_action);
        tvSnack.setTextColor(Color.WHITE);
        tvSnack.setTypeface(Typefaces.getRobotoMedium(getmContext()));
        tvSnackAction.setTypeface(Typefaces.getRobotoMedium(getmContext()));
        snackbar.show();

        Handler handlerUndo = new Handler();
        handlerUndo.postDelayed(new Runnable() {
            @Override
            public void run() {
                snackbar.dismiss();
            }
        }, 2500);
    }

    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        if (getItemViewType(fromPosition) != TYPE_CONTENT) {
            return;
        }

        if (fromPosition < toPosition) {
            for (int i = fromPosition - START_COUNT; i < toPosition - START_COUNT; i++) {
                Collections.swap(datas, i, i + 1);
            }
        } else {
            for (int i = fromPosition - START_COUNT; i > toPosition - START_COUNT; i--) {
                Collections.swap(datas, i, i - 1);
            }
        }
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public int getItemCount() {
        return datas.size() + START_COUNT + END_COUNT;
    }

    public void addItem(int position, TaskStepVo item) {

        datas.add(position, ServiceFactory.getInstance().getTaskService().addTaskStep(item));

        // 因添加了头尾布局，所以需要加上顶部
        notifyItemInserted(position + START_COUNT);
    }

    public int getContentSize() {
        return datas.size();
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        if (viewType == TYPE_HEAD) {
            return new HeadHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_default_header, viewGroup, false));
        } else if (viewType == TYPE_CONTENT) {
            return new ItemViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_taskdetail, viewGroup, false));
        } else if (viewType == TYPE_CONTENT_NEXT) {
            return new NextHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_taskdetail_next, viewGroup, false));
        } else if (viewType == TYPE_SET) {
            return new OperationHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_taskdetail_set, viewGroup, false));
        } else if (viewType == TYPE_REMARK) {
            return new RemarkHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_taskdetail_remark, viewGroup, false));
        } else {
            return new ButtomHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_default_bottom, viewGroup, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) { // 内容
            ItemViewHolder myHolder = (ItemViewHolder) holder;
            final TaskStepVo item = datas.get(position - START_COUNT);
            myHolder.setData(item);
        } else if (holder instanceof RemarkHolder) {
            RemarkHolder h = (RemarkHolder) holder;
            h.initData();
        }
    }

    public final static int START_COUNT = 1;
    public final static int END_COUNT = 4;

    public final static int TYPE_HEAD = 0;
    public final static int TYPE_CONTENT = 1;
    public final static int TYPE_CONTENT_NEXT = 2;
    public final static int TYPE_SET = 3;
    public final static int TYPE_REMARK = 4;
    public final static int TYPE_BUTTOM = 5;


    @Override
    public int getItemViewType(int position) {
        int contentSize = getContentSize() + START_COUNT;
        if (position == 0) { // 头部
            return TYPE_HEAD;
        } else if (position == contentSize) { // 下一步骤
            return TYPE_CONTENT_NEXT;
        } else if (position == contentSize + 1) { // 操作
            return TYPE_SET;
        } else if (position == contentSize + 2) { // 备注
            return TYPE_REMARK;
        } else if (position == contentSize + 3) { // 尾部
            return TYPE_BUTTOM;
        } else {
            return TYPE_CONTENT;
        }
    }

    // 中间的内容
    class ItemViewHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {

        @BindView(R.id.task_content_item_root_layout)
        FrameLayout itemLayout;
        @BindView(R.id.task_branch_text)
        ClickableTextView itemText;
        @BindView(R.id.task_branch_edit)
        MultilineEditText itemTextEdit;
        @BindView(R.id.task_branch_check)
        AppCompatCheckBox itemCheck;

        TaskStepVo data;

        public void setData(TaskStepVo data) {
            this.data = data;
            itemText.setText(data.getTitle());
            itemCheck.setChecked(data.isChk());
        }

        ItemViewHolder(final View v) {
            super(v);
            ButterKnife.bind(this, v);

            itemLayout = v.findViewById(R.id.task_content_item_root_layout);
            itemText = v.findViewById(R.id.task_branch_text);
            itemTextEdit = v.findViewById(R.id.task_branch_edit);
            itemCheck = v.findViewById(R.id.task_branch_check);

            itemText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    itemText.setVisibility(View.GONE);

                    itemTextEdit.setText(itemText.getText());
                    itemTextEdit.setVisibility(View.VISIBLE);

                    // 获得焦点
                    itemTextEdit.setFocusable(true);
                    itemTextEdit.setFocusableInTouchMode(true);
                    itemTextEdit.requestFocus();

                    /*EditText不会自动获取焦点并且不会弹出键盘代码：
                    将其父控件设置
                    Parent.setFocusable(true);
                    Parent.setFocusableInTouchMode(true);*/
                }
            });

            // 任务步骤编辑状态控制
            itemTextEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                        itemTextEdit.setVisibility(View.GONE);
                        itemText.setText(v.getText());
                        itemText.setVisibility(View.VISIBLE);
                    }
                    // 返回true，保留软键盘。false，隐藏软键盘
                    return true;
                }
            });


            itemTextEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (hasFocus) {
                        // 得到焦点

                        // 光标移动到末尾
                        itemTextEdit.setSelection(itemTextEdit.getText().length());

                        // 弹出键盘
                        InputMethodManager inputManager = (InputMethodManager) itemTextEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputManager.showSoftInput(itemTextEdit, 0);
                    } else {
                        // 失去焦点
                        itemTextEdit.setVisibility(View.GONE);
                        itemText.setText(itemTextEdit.getText());
                        itemText.setVisibility(View.VISIBLE);

                        if (!TextUtils.isEmpty(itemTextEdit.getText())) {
                            ServiceFactory.getInstance().getTaskService().saveTaskStepTitle(data.getId(), itemTextEdit.getText().toString());
                        }
                    }
                }
            });


            itemCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    ServiceFactory.getInstance().getTaskService().doStepFinish(data.getId(), b);
                    itemText.setTextColor(ContextCompat.getColor(getmContext(), b ? R.color.textHint : R.color.textDefault));
                    itemText.getPaint().setStrikeThruText(b);// setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                }
            });
        }

        @Override
        public void onItemSelected(Context context) {
        }

        @Override
        public void onItemClear(Context context) {
        }
    }

    // 步骤添加
    class NextHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.task_content_item_next_layout)
        LinearLayout itemLayout;
        @BindView(R.id.task_branch_next_text)
        ClickableTextView labTitle;
        @BindView(R.id.task_branch_next_edit)
        MultilineEditText labTitleEdit;
        @BindView(R.id.task_branch_next_check)
        AppCompatCheckBox itemCheck;
        @BindView(R.id.task_branch_next_img)
        ImageView itemImg;

        NextHolder(final View v) {
            super(v);
            ButterKnife.bind(this, v);

            labTitle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    labTitle.setVisibility(View.GONE);
                    itemImg.setVisibility(View.GONE);
                    labTitleEdit.setVisibility(View.VISIBLE);

                    // 设置不可用
                    itemCheck.setVisibility(View.VISIBLE);
                    itemCheck.setEnabled(false);

                    // 获得焦点
                    labTitleEdit.setFocusable(true);
                    labTitleEdit.setFocusableInTouchMode(true);
                    labTitleEdit.requestFocus();
                }
            });

            // 任务主干编辑状态控制
            labTitleEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                    if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {

                        labTitleEdit.setVisibility(View.GONE);
                        labTitle.setVisibility(View.VISIBLE);

                        itemImg.setVisibility(View.VISIBLE);
                        itemCheck.setVisibility(View.GONE);

                        if (!TextUtils.isEmpty(v.getText())) {
                            TaskStepVo item = new TaskStepVo();
                            item.setTaskId(DATA.getId());
                            item.setSort(getContentSize());
                            item.setChk(false);
                            item.setTitle(v.getText().toString());
                            addItem(getContentSize(), item);

                            // 清空数据
                            v.setText(null);

                            // 用于重复添加步骤 动态给EditText获得焦点并弹起软键盘
                            labTitle.setVisibility(View.GONE);
                            labTitleEdit.setText("");
                            labTitleEdit.setVisibility(View.VISIBLE);
                            labTitleEdit.setFocusable(true);
                            labTitleEdit.setFocusableInTouchMode(true);
                            labTitleEdit.requestFocus();
                        }
                    }
                    // 返回true，保留软键盘。false，隐藏软键盘
                    return true;
                }
            });

            labTitleEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (hasFocus) {
                        // 得到焦点

                        // 光标移动到末尾
                        labTitleEdit.setSelection(labTitleEdit.getText().length());

                        // 弹出键盘
                        InputMethodManager inputManager = (InputMethodManager) labTitleEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputManager.showSoftInput(labTitleEdit, 0);
                    } else {
                        // 失去焦点
                        labTitleEdit.setVisibility(View.GONE);
                        labTitle.setVisibility(View.VISIBLE);

                        itemCheck.setVisibility(View.GONE);
                        itemImg.setVisibility(View.VISIBLE);
                    }
                }
            });

            itemCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    labTitle.setTextColor(ContextCompat.getColor(v.getContext(), b ? R.color.textHint : R.color.textDefault));
                    labTitle.getPaint().setStrikeThruText(b);// setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                }
            });
            itemCheck.setChecked(false);
        }
    }

    // 操作
    public class OperationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        @BindView(R.id.layoutPreMinute)
        LinearLayout layoutPreMinute;
        @BindView(R.id.btnChoicePreMinute)
        TextView btnChoicePreMinute;
        @BindView(R.id.btnStartPreMinute)
        ImageView btnStartPreMinute;
        @BindView(R.id.tagTimer)
        ImageView tagTimer;

        @BindView(R.id.btnDeadline)
        LinearLayout btnDeadline;
        @BindView(R.id.labDeadline)
        TextView labDeadline;
        @BindView(R.id.tagDeadline)
        ImageView tagDeadline;
        @BindView(R.id.btnClearDeadline)
        ImageView btnClearDeadline;

        @BindView(R.id.btnRemind)
        LinearLayout btnRemind;
        @BindView(R.id.labRemind)
        TextView labRemind;
        @BindView(R.id.tagRemind)
        ImageView tagRemind;
        @BindView(R.id.btnClearRemind)
        ImageView btnClearRemind;

        @BindView(R.id.btnQuadrant)
        LinearLayout btnQuadrant;
        @BindView(R.id.labQuadrant)
        TextView labQuadrant;
        @BindView(R.id.tagQuadrant)
        ImageView tagQuadrant;
        @BindView(R.id.imgQuadrant)
        ImageView imgQuadrant;

        private PopupMenu menuQuadrant;
        private PopupMenu menuDeadline;
        private PopupMenu menuRemind;
        private CalcDateUtil calcDt;
        private boolean START_PRE_MINUTE = true;

        public OperationHolder(final View v) {
            super(v);
            ButterKnife.bind(this, v);

            // 计算时间
            calcDt = new CalcDateUtil();

            initMenus();
            initMenusData();
        }

        private void initMenusData() {

            // 优先级
            labQuadrant.setText(AppStatus.QuadrantLabArr[DATA.getQuadrant()]);
            imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[DATA.getQuadrant()]);
            //imgQuadrant.setColorFilter(ContextCompat.getColor(getmContext(), AppStatus.QuadrantColorArr[DATA.getQuadrant()]));

            // 预计时间
            btnChoicePreMinute.setText(String.format(getmContext().getResources().getString(R.string.task_pre_minute), DATA.getPreMinute()));

            // 提醒时间
            if (DATA.getRemindDt() != null) {
                labRemind.setText(calcDt.remindCustom(DATA.getRemindDt()));
                changeRemindView(true);
            }

            // 截止时间
            if (DATA.getDeadline() != null) {
                labDeadline.setText(calcDt.deadlineCustom(DateUtils.setEndTime(DATA.getDeadline())));
                changeDeadLineView(true);
            }
        }

        private void initMenus() {
            // 优先级
            menuQuadrant = new PopupMenu(getmContext(), labQuadrant);
            menuQuadrant.inflate(R.menu.menu_quadrant);
            menuQuadrant.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.m1:
                            DATA.setQuadrant(AppStatus.Quadrant.ONE);
                            break;
                        case R.id.m2:
                            DATA.setQuadrant(AppStatus.Quadrant.TWO);
                            break;
                        case R.id.m3:
                            DATA.setQuadrant(AppStatus.Quadrant.THREE);
                            break;
                        case R.id.m4:
                            DATA.setQuadrant(AppStatus.Quadrant.FOUR);
                            break;
                    }
                    labQuadrant.setText(item.getTitle());
                    imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[DATA.getQuadrant()]);
                    //imgQuadrant.setColorFilter(ContextCompat.getColor(getmContext(), AppStatus.QuadrantColorArr[DATA.getQuadrant()]));
                    ServiceFactory.getInstance().getTaskService().saveQuadrant(DATA.getId(), DATA.getQuadrant());
                    return false;
                }
            });


            // 截止日期
            menuDeadline = new PopupMenu(getmContext(), labDeadline);
            menuDeadline.inflate(R.menu.menu_task_set_card_deadline);
            menuDeadline.getMenu().findItem(R.id.deadline_item1).setTitle((String) calcDt.deadlineTodayArr[1]);
            menuDeadline.getMenu().findItem(R.id.deadline_item2).setTitle((String) calcDt.deadlineTomorrowArr[1]);
            menuDeadline.getMenu().findItem(R.id.deadline_item3).setTitle((String) calcDt.deadlineNextWeekMondayArr[1]);
            menuDeadline.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {

                    switch (item.getItemId()) {
                        case R.id.deadline_item1:
                            saveDateForDeadline((String) calcDt.deadlineTodayArr[2], (Date) calcDt.deadlineTodayArr[0]);
                            break;
                        case R.id.deadline_item2:
                            saveDateForDeadline((String) calcDt.deadlineTomorrowArr[2], (Date) calcDt.deadlineTomorrowArr[0]);
                            break;
                        case R.id.deadline_item3:
                            saveDateForDeadline((String) calcDt.deadlineNextWeekMondayArr[2], (Date) calcDt.deadlineNextWeekMondayArr[0]);
                            break;
                        case R.id.deadline_item4:
                            DatePickDialog d4 = new DatePickDialog(getmContext());
                            d4.setType(DateType.TYPE_YMD);
                            d4.setStartDate(DATA.getDeadline());
                            d4.setOnSureLisener(new OnSureLisener() {
                                @Override
                                public void onSure(Date date) {
                                    saveDateForDeadline(calcDt.deadlineCustom(DateUtils.setEndTime(date)), date);
                                }
                            });
                            d4.show();
                            break;
                    }
                    return false;
                }
            });

            // 提醒时间
            menuRemind = new PopupMenu(getmContext(), labRemind);
            menuRemind.inflate(R.menu.menu_task_set_card_remind);
            menuRemind.getMenu().findItem(R.id.remind_item1).setTitle((String) calcDt.remindTodayArr[1]);
            menuRemind.getMenu().findItem(R.id.remind_item2).setTitle((String) calcDt.remindTomorrowArr[1]);
            menuRemind.getMenu().findItem(R.id.remind_item3).setTitle((String) calcDt.remindNextWeekMondayArr[1]);
            menuRemind.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.remind_item1:
                            saveDateForRemind((String) calcDt.remindTodayArr[2], (Date) calcDt.remindTodayArr[0]);
                            break;
                        case R.id.remind_item2:
                            saveDateForRemind((String) calcDt.remindTomorrowArr[2], (Date) calcDt.remindTomorrowArr[0]);
                            break;
                        case R.id.remind_item3:
                            saveDateForRemind((String) calcDt.remindNextWeekMondayArr[2], (Date) calcDt.remindNextWeekMondayArr[0]);
                            break;
                        case R.id.remind_item4:
                            DatePickDialog d4 = new DatePickDialog(getmContext());
                            d4.setType(DateType.TYPE_ALL);
                            d4.setStartDate(DATA.getRemindDt());
                            d4.setOnSureLisener(new OnSureLisener() {
                                @Override
                                public void onSure(Date date) {
                                    saveDateForRemind(calcDt.remindCustom(date), date);
                                }
                            });
                            d4.show();
                            break;
                    }

                    return false;
                }
            });
        }

        private void saveDateForRemind(String lab, Date remindDt) {
            labRemind.setText(lab);
            DATA.setRemindDt(remindDt);
            ServiceFactory.getInstance().getTaskService().saveTaskRemind(DATA.getId(), remindDt);
            changeRemindView(true);
        }

        private void saveDateForDeadline(String lab, Date deadlineDt) {
            labDeadline.setText(lab);
            DATA.setDeadline(deadlineDt);
            ServiceFactory.getInstance().getTaskService().saveTaskDeadline(DATA.getId(), deadlineDt);
            changeDeadLineView(true);
        }

        private void changeDeadLineView(boolean isSet) {
            // 选中/清除状态
            btnClearDeadline.setVisibility(isSet ? View.VISIBLE : View.GONE);
            labDeadline.setTextColor(ContextCompat.getColor(getmContext(), isSet ? R.color.colorLink : R.color.colorThirdlyDark));
            tagDeadline.setColorFilter(ContextCompat.getColor(getmContext(), isSet ? R.color.colorLink : R.color.colorPrimary));
            labDeadline.setHint(getmContext().getResources().getString(R.string.deadline));

            // 如果截止时间超过当前时间则标红
            if (DATA.getDeadline() != null && DateUtils.compareDate(DATA.getDeadline(), new Date()) < 0) {
                labDeadline.setTextColor(ContextCompat.getColor(getmContext(), R.color.colorWarn));
                tagDeadline.setColorFilter(ContextCompat.getColor(getmContext(), R.color.colorWarn));
            }

            //if (DATA.getTaskType() == AppStatus.TaskType.GOAL || DATA.getTaskType() == AppStatus.TaskType.EVENT_INSERT) {
            // 任何任务都需要指定截止时间,不可以移除
            btnClearDeadline.setVisibility(View.GONE);
            //}
        }


        private void changeRemindView(boolean isSet) {

            // 选中/清除状态
            btnClearRemind.setVisibility(isSet ? View.VISIBLE : View.GONE);
            labRemind.setTextColor(ContextCompat.getColor(getmContext(), isSet ? R.color.colorLink : R.color.colorThirdlyDark));
            tagRemind.setColorFilter(ContextCompat.getColor(getmContext(), isSet ? R.color.colorLink : R.color.colorPrimary));
            labRemind.setHint(getmContext().getResources().getString(R.string.remind));

            // 如果提醒时间小于当前时间，则颜色恢复正常
            if (DATA.getRemindDt() != null && DateUtils.compareDateAndTime(DATA.getRemindDt(), new Date()) < 0) {
                labRemind.setTextColor(ContextCompat.getColor(getmContext(), R.color.colorThirdlyDark));
                tagRemind.setColorFilter(ContextCompat.getColor(getmContext(), R.color.colorPrimary));
            }
        }

        @OnClick({R.id.btnChoicePreMinute, R.id.btnStartPreMinute, R.id.btnDeadline, R.id.btnRemind, R.id.btnClearDeadline, R.id.btnClearRemind, R.id.btnQuadrant})
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btnQuadrant:
                    menuQuadrant.show();
                    break;
                case R.id.btnChoicePreMinute:
                    DatePickDialog d1 = new DatePickDialog(getmContext());
                    d1.setType(DateType.TYPE_CUSTOM_MINUTE_INTERVAL_5);
                    d1.setStartData(DATA.getPreMinute());
                    d1.setOnChangeLisener(null);
                    d1.setOnCustomSureLisener(new OnCustomSureLisener() {
                        @Override
                        public void onSure(Object obj) {
                            int minute = (int) obj;

                            ServiceFactory.getInstance().getTaskService().saveTaskPreMinute(DATA.getId(), minute);
                            btnChoicePreMinute.setText(String.format(getmContext().getResources().getString(R.string.task_pre_minute), minute));
                            DATA.setPreMinute(minute);
                        }
                    });
                    d1.show();
                    break;
                case R.id.btnStartPreMinute:
                    // 开始（停止）番茄时间
                    if (START_PRE_MINUTE) {
                        btnChoicePreMinute.setText(String.format(getmContext().getResources().getString(R.string.task_residue), DATA.getPreMinute() + ":00"));
                        btnChoicePreMinute.setTextColor(ContextCompat.getColor(getmContext(), R.color.colorLink));
                        tagTimer.setColorFilter(ContextCompat.getColor(getmContext(), R.color.colorLink));
                        btnStartPreMinute.setImageResource(START_PRE_MINUTE ? R.drawable.ic_small_close_gray3 : R.drawable.ic_play_green);
                        START_PRE_MINUTE = !START_PRE_MINUTE;

                        // 记录任务开始时间

                        // 开始计时任务
                    } else {
                        AlertUtils.tomatoDialog(getmContext(), (dialog, which) -> {
                            btnChoicePreMinute.setText(String.format(getmContext().getResources().getString(R.string.task_pre_minute), DATA.getPreMinute()));
                            btnChoicePreMinute.setTextColor(ContextCompat.getColor(getmContext(), R.color.colorThirdlyDark));
                            tagTimer.setColorFilter(ContextCompat.getColor(getmContext(), R.color.colorPrimary));
                            btnStartPreMinute.setImageResource(START_PRE_MINUTE ? R.drawable.ic_small_close_gray3 : R.drawable.ic_play_green);
                            START_PRE_MINUTE = !START_PRE_MINUTE;

                            // 清除任务开始时间

                            // 停止计时任务
                        });
                    }
                    break;
                case R.id.btnDeadline:
                    if (DATA.getTaskType() == AppStatus.TaskType.GOAL || DATA.getTaskType() == AppStatus.TaskType.STUDY) {
                        AlertUtils.showToast(getmContext(), getmContext().getResources().getString(R.string.dont_change_task));
                        return;
                    }
                    menuDeadline.show();
                    break;
                case R.id.btnRemind:
                    menuRemind.show();
                    break;
                case R.id.btnClearDeadline:
                    if (DATA.getTaskType() == AppStatus.TaskType.GOAL || DATA.getTaskType() == AppStatus.TaskType.STUDY) {
                        AlertUtils.showToast(getmContext(), getmContext().getResources().getString(R.string.dont_change_task));
                        return;
                    }
                    if (DATA.getTaskType() == AppStatus.TaskType.NORMAL) {
                        AlertUtils.showToast(getmContext(), getmContext().getResources().getString(R.string.dont_remove_task_deadline));
                        return;
                    }

                    ServiceFactory.getInstance().getTaskService().saveTaskDeadline(DATA.getId(), null);
                    DATA.setDeadline(null);
                    changeDeadLineView(false);
                    break;
                case R.id.btnClearRemind:
                    ServiceFactory.getInstance().getTaskService().saveTaskRemind(DATA.getId(), null);
                    DATA.setRemindDt(null);
                    changeRemindView(false);
                    break;
                default:
                    break;
            }
        }

        class CalcDateUtil {

            private Object[] deadlineTodayArr = new Object[3];
            private Object[] deadlineTomorrowArr = new Object[3];
            private Object[] deadlineNextWeekMondayArr = new Object[3];
            private Object[] remindTodayArr = new Object[3];
            private Object[] remindTomorrowArr = new Object[3];
            private Object[] remindNextWeekMondayArr = new Object[3];

            CalcDateUtil() {
                // 实际日期与时间
                deadlineTodayArr[0] = DateUtils.setEndTime();
                deadlineTomorrowArr[0] = DateUtils.setEndTime(DateUtils.moveDay(1));
                deadlineNextWeekMondayArr[0] = DateUtils.setEndTime(DateUtils.getNextWeekMonday());
                remindTodayArr[0] = DateUtils.moveHour(5); // 当前时间往后5小时
                remindTomorrowArr[0] = DateUtils.moveDayAndSetHour(new Date(), 1, 9);
                remindNextWeekMondayArr[0] = DateUtils.setTime(DateUtils.getNextWeekMonday(), 9, 0, 0, 0);

                // 菜单上显示的值
                deadlineTodayArr[1] = doFormat(R.string.deadline_m1, DateUtils.date2str((Date) deadlineTodayArr[0], DateUtils.F60));
                deadlineTomorrowArr[1] = doFormat(R.string.deadline_m2, DateUtils.date2str((Date) deadlineTomorrowArr[0], DateUtils.F60));
                deadlineNextWeekMondayArr[1] = doFormat(R.string.deadline_m3, DateUtils.date2str((Date) deadlineNextWeekMondayArr[0], DateUtils.F60));
                remindTodayArr[1] = doFormat(R.string.remind_m1, DateUtils.date2str((Date) remindTodayArr[0], DateUtils.F65));
                remindTomorrowArr[1] = doFormat(R.string.remind_m2, DateUtils.date2str((Date) remindTomorrowArr[0], DateUtils.F64));
                remindNextWeekMondayArr[1] = doFormat(R.string.remind_m3, DateUtils.date2str((Date) remindNextWeekMondayArr[0], DateUtils.F64));

                // 内容栏上显示的内容
                deadlineTodayArr[2] = doFormat(R.string.deadline_lab, "今天");
                deadlineTomorrowArr[2] = doFormat(R.string.deadline_lab, "明天");
                deadlineNextWeekMondayArr[2] = doFormat(R.string.deadline_lab, DateUtils.date2str((Date) deadlineNextWeekMondayArr[0], DateUtils.F31));
                remindTodayArr[2] = doFormat(R.string.remind_lab, "今天" + DateUtils.date2str((Date) remindTodayArr[0], DateUtils.F65));
                remindTomorrowArr[2] = doFormat(R.string.remind_lab, "明天" + DateUtils.date2str((Date) remindTomorrowArr[0], DateUtils.F65));
                remindNextWeekMondayArr[2] = doFormat(R.string.remind_lab, DateUtils.date2str((Date) remindNextWeekMondayArr[0], DateUtils.F33));
            }

            /**
             * 通用格式
             **/

            String remindCustom(Date date) {
                if (DateUtils.sameDate(date, new Date())) {
                    return doFormat(R.string.remind_lab, "今天" + DateUtils.date2str(date, DateUtils.F65));
                } else if (DateUtils.sameDate(date, DateUtils.moveDay(1))) {
                    return doFormat(R.string.remind_lab, "明天" + DateUtils.date2str(date, DateUtils.F65));
                }
                return doFormat(R.string.remind_lab, DateUtils.date2str(date, DateUtils.F33));
            }

            String deadlineCustom(Date date) {
                if (DateUtils.sameDate(date, new Date())) {
                    return doFormat(R.string.deadline_lab, "今天");
                } else if (DateUtils.sameDate(date, DateUtils.moveDay(1))) {
                    return doFormat(R.string.deadline_lab, "明天");
                }
                return doFormat(R.string.deadline_lab, DateUtils.date2str(date, DateUtils.F31));
            }

            private String doFormat(int id, String arg) {
                return String.format(getmContext().getResources().getString(id), arg);
            }

        }

    }

    // 备注
    public class RemarkHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.labRemark)
        TextView labRemark;
        @BindView(R.id.labRemarkDt)
        TextView labRemarkDt;

        public RemarkHolder(View v) {
            super(v);
            ButterKnife.bind(this, v);
            initData();
        }

        @OnClick({R.id.remarkLayout})
        public void onViewClicked(View v) {
            switch (v.getId()) {
                case R.id.remarkLayout:
                    showDialog();
                    break;
                default:
                    break;
            }
        }

        public void initData() {
            if (DATA.getId() != 0) {
                Remark r = ServiceFactory.getInstance().getRemarkService().getRemark(AppStatus.RemarkType.TASK, DATA.getId());
                if (r != null) {
                    labRemark.setText(r.getContent());
                    labRemarkDt.setText(String.format(getmContext().getResources().getString(R.string.update_time), DateUtils.date2str(r.getUpdatedDt(), DateUtils.F31)));
                    labRemarkDt.setVisibility(View.VISIBLE);
                } else {
                    labRemark.setText("");
                    labRemarkDt.setVisibility(View.GONE);
                }
            }
        }

        private Dialog mShareDialog;
        private View dialogView;

        private void showDialog() {
            if (mShareDialog == null) {
                initShareDialog();
            }
            refreshDialogData();
            mShareDialog.show();
        }

        private void refreshDialogData() {
            Remark remark = ServiceFactory.getInstance().getRemarkService().getRemark(AppStatus.RemarkType.TASK, DATA.getId());
            boolean noExist = remark == null;

            TextView labDate = dialogView.findViewById(R.id.labDate);
            labDate.setText(noExist ? "" : String.format(getmContext().getResources().getString(R.string.update_time), DateUtils.date2str(remark.getUpdatedDt(), DateUtils.F33)));
            labDate.setVisibility(noExist ? View.GONE : View.VISIBLE);

            MultilineEditText editContent = dialogView.findViewById(R.id.editContent);
            editContent.setText(noExist ? "" : remark.getContent());
        }

        private void initShareDialog() {
            dialogView = View.inflate(getmContext(), R.layout.activity_taskdetail_remark, null);
            dialogView.findViewById(R.id.btnBack).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    initData();
                    mShareDialog.dismiss();
                }
            });
            dialogView.findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertUtils.dialog(getmContext(), getmContext().getResources().getString(R.string.alt_clear_remark),
                            getmContext().getResources().getString(R.string.op_determine),
                            getmContext().getResources().getString(R.string.op_cancel), (dialog, which) -> {
                                ServiceFactory.getInstance().getRemarkService().clearRemark(AppStatus.RemarkType.TASK, DATA.getId());
                                refreshDialogData();
                            }, null);
                }
            });
            dialogView.findViewById(R.id.btnSave).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MultilineEditText editContent = dialogView.findViewById(R.id.editContent);
                    if (!TextUtils.isEmpty(editContent.getText())) {
                        ServiceFactory.getInstance().getRemarkService().saveRemark(AppStatus.RemarkType.TASK, DATA.getId(), editContent.getText().toString());
                        initData();
                        mShareDialog.dismiss();
                    }
                }
            });


            mShareDialog = new Dialog(getmContext(), R.style.dialog_full);
            mShareDialog.setCanceledOnTouchOutside(true);
            mShareDialog.setCancelable(true);

            Window window = mShareDialog.getWindow();
            assert window != null;
            window.setWindowAnimations(R.style.share_animation);
            window.setContentView(dialogView);
            window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);//设置横向全屏


            /**
             * 动态给EditText获得焦点并弹起软键盘
             */
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            MultilineEditText editContent = dialogView.findViewById(R.id.editContent);
            editContent.setFocusable(true);
            editContent.setFocusableInTouchMode(true);
            editContent.requestFocus();
            InputMethodManager imm = (InputMethodManager) getmContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editContent, 0);
        }
    }

    // 头部内容
    public class HeadHolder extends RecyclerView.ViewHolder {
        public HeadHolder(View itemView) {
            super(itemView);
        }
    }

    // 尾部内容
    public class ButtomHolder extends RecyclerView.ViewHolder {
        public ButtomHolder(View itemView) {
            super(itemView);
        }
    }

}
